<template>
  <div class="container">
    <div v-if="posterList.length === 0" style="text-align:center;color:#ccc;font-size:24rpx">暂时没有海报</div>
    <div v-else>
      <!-- <swiper :previous-margin="posterMargin+ 'px'" :next-margin="posterMargin+ 'px'" :current="current" :style="{height:swiperHeight}" @animationfinish="changePoster"> -->
      <swiper :current="current" :style="{height:swiperHeight}" @animationfinish="changePoster">
        <block v-for="(item,index) in posterList" :key="index">
          <swiper-item class="swiper-item"  v-if="item.imageUrl">
            <canvas :canvas-id="'shareCanvas'+index"  :style="{width: swiperItemWidth + 'px !important',height:'100%'}"></canvas>
          </swiper-item>
        </block>
      </swiper>
      <div v-if="total > 0" style="display:flex;justify-content: center;width:268rpx;margin: 0 auto" class="pad-t-10">
        <span v-if="current+1 !== 1" class="arrow" @click="clickChangePoster('less')">
          <van-icon name="arrow-left" />
        </span>
        <span v-else class="arrow" style="opacity: 0;"></span>
        <span style="flex:1;text-align:center">{{current+1}}/{{total}}</span>
        <span v-if="current+1 !== total" class="arrow" @click="clickChangePoster('plus')">
          <van-icon name="arrow"/>
        </span>
        <span v-else class="arrow" style="opacity: 0;"></span>
      </div>
      <div class="mar-10" @click="saveToAlbum(current)">
        <button size="default" class="primary-button">保存到相册</button>
      </div>
    </div>
    <div class="pad-10"></div>
  </div>
</template>

<script>
import {
  getMemberInfo
} from '@/api/home'
import {
  pageDailyPoster
} from '@/api/personal'

export default {
  data() {
    return {
      today: '2019-03-03',
      memberInfo: {},
      poster: {
        imageUrl: ''
      },
      size: 10, // 海报每页的个数
      current: 0, // 当前显示的海报索引值
      currentPage: 1, // 当前页数
      posterList: [], // 海报信息列表
      lastIndex: 0, // 当前页最后一张图片的下标
      finger: null, // 保存二维码图片信息
      posterMargin: '',
      swiperItemWidth: '',
      swiperHeight: '',
      total: '' // 海报总数
    }
  },
  onLoad() {
    // 初始化data
    Object.assign(this.$data, this.$options.data())
  },
  beforeMount() {
    this.swiperItemWidth = this.$pt.getSystemInfoSync().windowWidth * 0.8
    // this.posterMargin = this.$pt.getSystemInfoSync().windowWidth * 0.8 / 4 - this.$pt.getSystemInfoSync().windowWidth * 0.053
    this.posterMargin = (this.$pt.getSystemInfoSync().windowWidth - (this.$pt.getSystemInfoSync().windowWidth * 0.8)) / 4
    this.swiperHeight = this.$pt.getSystemInfoSync().screenHeight * 0.73 + 'px'
  },
  mounted() {
    this.getMemberInfo()
  },
  onShow() {
    // this.getMemberInfo()
  },
  methods: {
    changePoster(e) {
      if (e.target.source) {
        this.current = e.mp.detail.current
        if (this.current === this.posterList.length - 1) {
          this.currentPage++
          this.getDailyPoster()
        }
      }
    },
    clickChangePoster(type) {
      this.current = type === 'plus' ? this.current + 1 : this.current - 1
      if (this.current !== 0 && this.current < this.total && this.current % 10 === 0) {
        this.currentPage++
        this.getDailyPoster()
      }
    },
    getMemberInfo() {
      getMemberInfo(this.getCustomerId).then(response => {
        if (response.isError) return
        this.memberInfo = response.data
        this.getDailyPoster()
      })
    },
    getDailyPoster() {
      this.$utils.showToast({
        title: '图片生成中',
        icon: 'loading',
        duration: 100000
      })
      pageDailyPoster(this.getCustomerId, this.currentPage, this.size).then((response) => {
        if (response.isError) return
        if (response.data.records.length === 0) {
          this.$pt.hideToast()
          return
        }
        this.total = response.data.total
        this.posterList.push(...response.data.records)
        for (let i = this.lastIndex; i < this.posterList.length; i++) {
          let id = `shareCanvas${i}`
          if (this.posterList[i].imageUrl) {
            this.drawPage(id, i)
          } else {
            this.$pt.hideToast()
          }
          this.lastIndex = i + 1
        }
      }).catch(() => {
      })
    },
    drawPage(id, index) {
      const that = this
      // canvas 使用的是px，如果要适应屏幕需要转化
      let rpx = 0.8
      const context = that.$pt.createCanvasContext(id)
      // 清除画布，防止层叠
      context.clearRect(0, 0, this.swiperItemWidth, 700 * rpx)
      // 背景色
      // context.rect(0, 0, that.$pt.getSystemInfoSync().windowWidth * 0.8, that.$pt.getSystemInfoSync().screenHeight * 0.776)
      context.rect(0, 0, this.swiperItemWidth, 800 / (621 / (this.swiperItemWidth)) + 170)
      context.setFillStyle('#ffffff')
      context.fill()
      // 还原字体颜色
      context.setFillStyle('#333333')
      // 头像
      context.beginPath()
      // 昵称
      context.setFontSize(12)
      // context.fillText(that.$utils.getStrByLength(`分享者：${that.memberInfo.nickname}`, 16), 152 * rpx, that.$pt.getSystemInfoSync().screenHeight * 0.6 + 70)
      context.fillText(that.$utils.getStrByLength(`分享者：${that.memberInfo.nickname}`, 16), 152 * rpx, 800 / (621 / (this.swiperItemWidth)) + 70)
      // 默认字体
      context.setFillStyle('#333333')
      context.setFontSize(16)
      // 二维码
      if (that.finger) {
        // context.drawImage(that.finger.tempFilePath, 39 * rpx, that.$pt.getSystemInfoSync().screenHeight * 0.6 + 20, 95 * rpx, 95 * rpx)
        context.drawImage(that.finger.tempFilePath, 39 * rpx, 800 / (621 / (this.swiperItemWidth)) + 15, 95 * rpx, 95 * rpx)
        context.draw(true)
      } else {
        that.downloadFile(that.memberInfo.wxaCode, true).then(wxaCode => {
          // context.drawImage(wxaCode.tempFilePath, 39 * rpx, that.$pt.getSystemInfoSync().screenHeight * 0.6 + 20, 95 * rpx, 95 * rpx)
          context.drawImage(that.finger.tempFilePath, 39 * rpx, 800 / (621 / (this.swiperItemWidth)) + 15, 95 * rpx, 95 * rpx)
          context.draw(true)
        })
      }
      // 长按提醒
      context.setFontSize(15)
      // context.fillText('长按识别小程序', 152 * rpx, that.$pt.getSystemInfoSync().screenHeight * 0.6 + 50)
      context.fillText('长按识别小程序', 152 * rpx, 800 / (621 / (this.swiperItemWidth)) + 50)
      // 海报
      that.downloadFile(that.posterList[index].imageUrl).then(finger => {
        context.drawImage(finger.tempFilePath, 0, 0, this.swiperItemWidth, 800 / (621 / (this.swiperItemWidth)))
        // context.drawImage(finger.tempFilePath, 0, 0, that.$pt.getSystemInfoSync().windowWidth * rpx, that.$pt.getSystemInfoSync().screenHeight * 0.6)
        context.draw(true)
        if (index === that.posterList.length - 1) {
          this.$pt.hideToast()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    downloadFile(url, iswxcode = false) {
      let that = this
      return new Promise((resolve, reject) => {
        if (url) {
          this.$pt.downloadFile({
            url: url,
            success: function(finger) {
              if (iswxcode) {
                that.finger = finger
              }
              resolve(finger)
            },
            fail: function(err) {
              reject(err)
            }
          })
        }
      })
    },
    saveToAlbum: function(index) {
      const that = this
      that.$pt.canvasToTempFilePath({
        canvasId: `shareCanvas${index}`,
        success: (res) => {
          const filePath = res.tempFilePath
          if (filePath) {
            that.$pt.saveImageToPhotosAlbum({
              filePath: filePath,
              success: (res) => {
                that.$utils.showToast({ title: '保存成功，请到手机相册查看' })
              },
              fail: function(err) {
                if (err.errMsg.indexOf('cancel') !== -1) return
                that.$pt.showModal({
                  content: '保存图片需要访问你的相册',
                  success(res) {
                    if (res.confirm) {
                      that.$pt.openSetting()
                    } else if (res.cancel) {
                      console.log(err)
                    }
                  }
                })
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.container {
  padding-top: 30rpx;
}
.primary-button {
  background-color: #f8c400;
  border-radius: 50rpx;
  font-size: 36rpx;
  border: none;
  width: 268rpx;
  height: 88rpx;
  color: #343434;
  padding: 0rpx 40rpx 0rpx 40rpx;
}
.change-bar {
  position: absolute;
  right: 10px;
  top: 10px;
  z-index: 10;
  border-radius: 100px;
  padding: 6px 10px;
  background: rgba(246, 246, 246, 0.8);
  z-index: 10;
}
.share-canvas {
  width: 100%;
  height: 700px;
  background-color: #fff;
}

.swiper-item {
  display: flex;
  justify-content: center;
}
.slide-image {
  height: 903.9rpx;
  /* width: 254.14px; */
  margin-top: 66rpx;
}
.active {
  height: 1035rpx;
}
.arrow{
  background: #ddd;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  justify-content: center;
  color: #fff;
}
</style>
